package ru.diamond.home;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Server {
	
	@Override
	protected void finalize() throws Throwable {
		stop();
		super.finalize();
	}

	private ServerSocket ss;
	private Thread listener;
	private Listener impl; 
	private List<ClientSocket> clients = Collections.synchronizedList(new ArrayList<ClientSocket>());
	public static final SimpleDateFormat sdf = new SimpleDateFormat("YYYY.MM.dd HH:mm:ss");
	
	public Server(int port) throws Exception
	{
		 ss = new ServerSocket(port);
		 ss.setSoTimeout(100);
		 impl = new Listener();
		 listener = new Thread(impl) ;
		 listener.start();
	}
	
	
	public void stop()
	{
		for (ClientSocket s : clients)
			s.stopClient();
		
		impl.isOn = false;
	}
	
	
	private class Listener implements Runnable{

		public boolean isOn = true;
		@Override
		public void run() {
			// TODO Auto-generated method stub
			System.out.println(sdf.format(new Date()) + "\t Server started");
			while(isOn)
			{
				try {
					Socket socket = ss.accept();
					ClientSocket clnt = new ClientSocket(socket);
					clients.add(clnt);
				}
				catch (Exception e) {
					if (e instanceof SocketTimeoutException) continue;
					e.printStackTrace();
					isOn = false;
				}
				
				
			}
			System.out.println(sdf.format(new Date()) + "\t Server closed");
		}
	
	}
			
	
	
	
	

}
